/* @(#)GSBargainProcessor.java    V0.1
 *
 * Project: GSdevelop
 *
 * Modify Information:
 * =============================================================================
 *   Author       Date       Description
 *   ------------ ---------- ---------------------------------------------------
 *   owen         2006-4-20
 *   Jenny        2006-4-27  添加方法getBargainInfo
 * Copyright Notice:
 * =============================================================================
 *    Copyright (c) 2001-2006 Beijing HiTRUST Technology Co., Ltd. 1808 Room, 
 *        Science & Technology Building, No. 9 South Street, Zhong Guan Cun, 
 *        Haidian District, Beijing ,100081, China All rights reserved.
 *
 *    This software is the confidential and proprietary information of
 *        Beijing HiTRUST Technology Co., Ltd. ("Confidential Information").
 *        You shall not disclose such Confidential Information and shall use it
 *        only in accordance with the terms of the license agreement you entered
 *        into with HiTRUST.
 *
 * Warning:
 * =============================================================================
 * 
 */
package com.hitrust.gs.business;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.util.ArrayList;

import javax.servlet.ServletOutputStream;

import org.apache.struts.upload.FormFile;

import com.hitrust.gs.bean.GSBargainBean;
import com.hitrust.gs.bean.GSBargainChargeBean;
import com.hitrust.gs.bean.GSBargainModfiyBean;
import com.hitrust.gs.dao.GSBargainDAO;
import com.hitrust.gs.lib.GSLogWriter;
import com.hitrust.gs.lib.GSSystemConfigurator;
import com.hitrust.gs.service.GSBaseForm;
import com.hitrust.gs.service.GSBaseManager;
import com.hitrust.gs.service.GSBaseProcesser;
import com.hitrust.gs.util.date.DateUtil;
import com.hitrust.gs.util.exception.GSException;
import com.hitrust.gs.util.page.ResultProcess;
import com.hitrust.gs.vo.GSBargainInfoVO;
import com.hitrust.gs.vo.GSBargainQueryVO;


/**
 * 
 */
public class GSBargainProcessor implements GSBaseProcesser{
   /**
    * 新增合同信息
    * @param aGSBargainBean
    * @throws GSException
    */
    public static void addBargainTask(GSBargainBean aGSBargainBean)throws GSException {
        GSBargainDAO tGSBargainDAO = new GSBargainDAO();
            //判断合同是否存在
             if (tGSBargainDAO.isExist(aGSBargainBean.getGs_bgn_serial())) {
                          throw new GSException("该合同已经存在");
              }
            //判断是否存在主合同
             if(aGSBargainBean.getGs_bgn_type().equals("2")){
               if (tGSBargainDAO.isExist(aGSBargainBean.getGs_bgn_mainserial())==false) {
                 throw new GSException("主合同不存在");
              }
               if(tGSBargainDAO.typeID(aGSBargainBean.getGs_bgn_mainserial()).equals("2")){
                 throw new GSException("该合同为副合同,不能成为主合同编号");  
               }
             }
            //添加机构信息
            if (tGSBargainDAO.addBargain(aGSBargainBean) == false) {
                throw new GSException("添加合同信息失败！");
              }
        }
    /**
     * 判断是否可以新增合同信息
     * @param aGSBargainBean
     * @throws GSException
     */
    public static void permitAddBargainTask(GSBargainBean aGSBargainBean)throws GSException{
        GSBargainDAO tGSBargainDAO = new GSBargainDAO();
        //判断合同是否存在
        if (tGSBargainDAO.isExist(aGSBargainBean.getGs_bgn_serial())) {
                     throw new GSException("该合同已经存在");
         }
       //判断是否存在主合同
        if(aGSBargainBean.getGs_bgn_type().equals("2")){
          if (tGSBargainDAO.isExist(aGSBargainBean.getGs_bgn_mainserial())==false) {
            throw new GSException("主合同不存在");
         }
          if(tGSBargainDAO.typeID(aGSBargainBean.getGs_bgn_mainserial()).equals("2")){
              throw new GSException("该合同为副合同,不能成为主合同编号");  
            }
        }
    }
    /**
     * 
     * @param aGSBargainBean
     * @throws GSException
     */
    public static void addBargainChargeTask(GSBargainChargeBean aGSBargainChargeBean)throws GSException {
        GSBargainDAO tGSBargainDAO = new GSBargainDAO();
            
            //添加合同信息
            if (tGSBargainDAO.addBargainCharge(aGSBargainChargeBean) == false) {
                throw new GSException("添加合同费用信息失败！");
            }
        }
    
    public static void saveFile(FormFile aFile,String aPath,String aSaveName) throws GSException {

        File file = null;
        FileOutputStream fos = null;
        try{
            if (aFile.getFileSize() == 0) {
                     throw new GSException("当前文件不存在或为空");
                 }
            if (aFile.getFileSize() > 3145728 ){
                     throw new GSException("上传文件不能超过3M");
                 }
            else{
               
                String realFilePath = aPath+System.getProperty("file.separator")+aSaveName;
                //String filename = "/upload/"+aSaveName;
                file = new File(realFilePath);
                fos = new FileOutputStream(file);
                fos.write(aFile.getFileData());
                //file.delete();
                fos.flush();
                //dao.insert(vo);
                fos.close();
            }
        }catch(IOException ioe){
            throw new GSException (GSException.E17793,GSException.E17793_MSG);
        }
    }
    
    /**
     * 取得合同信息详细信�息
     * @param aBgnSerial
     * @return GSBargainBean
     * @throws GSException
     */
    public static GSBargainBean getBargainDetail(String aBgnSerial) throws GSException{
        GSBargainBean tGSBargainBean = new GSBargainBean();
        try{
            GSBargainDAO tGSBargainDAO = new GSBargainDAO();
            //执行查询
            tGSBargainBean = tGSBargainDAO.queryBargain(aBgnSerial);
        }catch(GSException e){
            throw e;
        }catch(Exception e){
            GSLogWriter.error(e.toString());
            throw new GSException(GSException.E10022,GSException.E10022_MSG);
        }
        return tGSBargainBean;
    }

    /**
     * 查询合同费用信息
     * @param aBgnSerial
     * @return        
     * @throws GSException
     */
    public static ArrayList getBargainCharge(String aBgnSerial) throws GSException{
        ArrayList tList=new ArrayList();
        try{
            GSBargainDAO tGSBargainDAO = new GSBargainDAO();
            tList = tGSBargainDAO.queryBargainCharge(aBgnSerial);
            
        }catch(GSException e){
            throw e;
        }catch(Exception e){
            GSLogWriter.error(e.toString());
            throw new GSException(GSException.E10021,GSException.E10021_MSG);
        }
        return tList;
    }
    
    /**
     * 按条件合同费用信息
     * 
     * @param 
     *        
     * @return
     * @throws GSException
     */
    public ArrayList getSearchBargain(GSBargainQueryVO aGSBargainQueryVO) throws GSException {
        ArrayList tBargainList = new ArrayList();
        ResultProcess tResultProcess = new ResultProcess();
        GSBargainDAO tGSBargainDAO = new GSBargainDAO();
        ArrayList tList = new ArrayList();
        Connection tConn = null;
        try {
            // 取得DB连接
            tConn = tGSBargainDAO.getConnetion();
           
            String[] tDateStr = new String[2];
            // 取得查询签约日期创建最小日期和最大日期
            tDateStr[0] = aGSBargainQueryVO.startsigndate;
            tDateStr[1] = aGSBargainQueryVO.endsigndate;
            // 格式化日期
            tDateStr = DateUtil.formateDate(tDateStr);
            aGSBargainQueryVO.startsigndate = tDateStr[0];
            aGSBargainQueryVO.endsigndate = tDateStr[1];
            
            //取得查询归卷日期创建最小日期和最大日期
            tDateStr[0] = aGSBargainQueryVO.startreturneddate;
            tDateStr[1] = aGSBargainQueryVO.endreturneddate;
            // 格式化日期
            tDateStr = DateUtil.formateDate(tDateStr);
            aGSBargainQueryVO.startreturneddate = tDateStr[0];
            aGSBargainQueryVO.endreturneddate = tDateStr[1];
            
            //取得查询终止日期创建最小日期和最大日期
            tDateStr[0] = aGSBargainQueryVO.startenddate;
            tDateStr[1] = aGSBargainQueryVO.stopenddate;
            // 格式化日期
            tDateStr = DateUtil.formateDate(tDateStr);
            aGSBargainQueryVO.startenddate = tDateStr[0];
            aGSBargainQueryVO.stopenddate = tDateStr[1];
            // 查询所有订单及明细
            
            tBargainList = tGSBargainDAO.searchBargain(tConn,aGSBargainQueryVO);
            if (tBargainList.size() > 0) {
            
                for (int i = 0; i < tBargainList.size(); i++) {

                    GSBargainBean tGSBargainBean = (GSBargainBean) tBargainList.get(i);
                   
                    String[] tStr = new String[15];
                    tStr[0] = tGSBargainBean.getGs_bgn_content();
                    tStr[1] = tGSBargainBean.getGs_bgn_userid();
                    tStr[2] = GSBaseManager.getBargain(tGSBargainBean.getGs_bgn_type());
                    tStr[3] = tGSBargainBean.getGs_bgn_number();
                    tStr[4] = tGSBargainBean.getGs_bgn_filenumber();
                    tStr[5] = tGSBargainBean.getGs_bgn_department();
                    tStr[6] = tGSBargainBean.getGs_bgn_signuser();
                    tStr[7] = tGSBargainBean.getGs_bgn_signdate();
                    tStr[8] = tGSBargainBean.getGs_bgn_enddate();
                    tStr[9] = tGSBargainBean.getGs_bgn_term();
                    tStr[10] = tGSBargainBean.getGs_bgn_vol();
                    tStr[11] = tGSBargainBean.getGs_bgn_serial();
                    tStr[12] = tGSBargainBean.getGs_bgn_returneddate();
                    tStr[13] = GSBaseManager.getEffect(tGSBargainBean.getGs_bgn_effect());
                    tStr[14] = tGSBargainBean.getGs_bgn_id();
            
                    tList.add(tStr);
                }   
            }
            tResultProcess.setResult(tList); 
        } catch (GSException ge) {
            throw ge;
        } catch (Exception e) {
            GSLogWriter.debug(this, e.toString());
            throw new GSException(GSException.E10041, GSException.E10041_MSG);
        } finally {
            GSBargainDAO.close(tConn);
        }
        return tList;
    }
    /**
     * 查询合同明细信息
     * @param aBgnId        序号
     * @param aBgnSeral     编号
     * @return
     * @throws GSException
     */
    public GSBargainInfoVO getBargainInfo(String aBgnId,String aBgnSeral) throws GSException{
    	GSBargainInfoVO tVO = new GSBargainInfoVO();
    	GSBargainDAO tBargainDAO = new GSBargainDAO();
    	try{
            //查询合同信息
	    	GSBargainBean tBargainBean = tBargainDAO.queryBargain(aBgnId);
	    	if(tBargainBean != null){
		    	tVO.bgnId = tBargainBean.getGs_bgn_id();
		    	tVO.bgnSerial = tBargainBean.getGs_bgn_serial();
		    	tVO.bgnCont = tBargainBean.getGs_bgn_content();
		    	tVO.bgnType = tBargainBean.getGs_bgn_type();
		    	tVO.custName = tBargainBean.getGs_bgn_userid();
		    	tVO.custType = tBargainBean.getGs_bgn_usertype();
		    	tVO.deptId = tBargainBean.getGs_bgn_department();
		    	tVO.signPerson = tBargainBean.getGs_bgn_signuser();
		    	tVO.signDate = DateUtil.formatDate(tBargainBean.getGs_bgn_signdate());
		    	tVO.endDate = tBargainBean.getGs_bgn_enddate().equals("")?"":DateUtil.formatDate(tBargainBean.getGs_bgn_enddate());
		    	tVO.fileCount = tBargainBean.getGs_bgn_filenumber();
		    	tVO.fileName = tBargainBean.getGs_bgn_filename();
		    	tVO.mainSerial = tBargainBean.getGs_bgn_mainserial();
		    	tVO.pageCount = tBargainBean.getGs_bgn_number();
		    	tVO.returnDate = tBargainBean.getGs_bgn_returneddate().equals("")?"":DateUtil.formatDate(tBargainBean.getGs_bgn_returneddate());
		    	tVO.term = tBargainBean.getGs_bgn_term();
		    	tVO.vol = tBargainBean.getGs_bgn_vol();
		    	tVO.notes = tBargainBean.getGs_bgn_remark();
		    	ArrayList tBargainChargeBean = tBargainDAO.queryBargainCharge(aBgnId);//根据合同序号查询合同费用信息
		    	tVO.chargeList = tBargainChargeBean;
                tVO.week = tBargainBean.getGs_bgn_week();
	    	}else{
	    		GSLogWriter.error(this,"查询不到合同信息");
	    		throw new GSException("查询不到合同信息");
	    	}
    	}catch(GSException ge){
    		throw ge;
    	}catch(Exception e){
    		GSLogWriter.error(this,e.toString());
    		throw new GSException(GSException.E00001,GSException.E00001_MSG);
    	}
    	return tVO;
    }
    
    /**
     * 修改合同信息为无效
     * @param aGSBargainBean
     * @throws GSException
     */
    public static void modifyBargainEffectTask(String aBgnEffect,String aBgnSerial)throws GSException {
        GSBargainDAO tGSBargainDAO = new GSBargainDAO();
        GSBargainBean tGSBargainBean = new GSBargainBean();
        tGSBargainBean=tGSBargainDAO.queryBargain(aBgnSerial);
            if (tGSBargainDAO.modifyBargainEffect(aBgnEffect,aBgnSerial) == false) {
                throw new GSException("修改合同信息为无效失败！");
            }
            if(tGSBargainBean.getGs_bgn_type().equals("1")){
                if (tGSBargainDAO.modifyLowerBargainEffect(aBgnEffect,tGSBargainBean.getGs_bgn_mainserial()) == false) {
                    throw new GSException("修改副合同信息为无效失败！");
                } 
            }
        }
    
    /**
     * 删除合同信息
     * @param aBgnSerial
     * @throws GSException
     */
    public static void deleteBargainTask(String aBgnSerial,String aPath)throws GSException {
        GSBargainDAO tGSBargainDAO = new GSBargainDAO();
        GSBargainBean tGSBargainBean = new GSBargainBean();
        
        tGSBargainBean=tGSBargainDAO.queryBargain(aBgnSerial);
        String filename=tGSBargainBean.getGs_bgn_filename();
        String realFilePath = aPath+"\\"+filename;
        File  tFile = new File(realFilePath);
        //文件删除
        tFile.delete();
        
            if (tGSBargainDAO.deleteBargain(aBgnSerial) == false) {
                throw new GSException("删除合同信息失败！");
            }
           ArrayList tList1=new ArrayList();
           tList1=tGSBargainDAO.queryBargainCharge(aBgnSerial);
           if(tList1.size()>0){ 
            if (tGSBargainDAO.deleteBargainCharge(aBgnSerial) == false) {
                throw new GSException("删除合同费用信息失败！");
            }
           }
           
          //删除主合同中的副合同
           if(tGSBargainBean.getGs_bgn_type().equals("1")){
             ArrayList tList2=new ArrayList();
             tList2=tGSBargainDAO.queryMainBargain(tGSBargainBean.getGs_bgn_serial());
             if(tList2.size()>0){ 
              if (tGSBargainDAO.deleteLowerBargain(tGSBargainBean.getGs_bgn_serial()) == false) {
                throw new GSException("删除主合同所属副合同信息失败！");
               }
            }
           }
        }
    
    /**
     * 修改合同信息
     * @param aGSBargainBean
     * @throws GSException
     */
     public static void modifyBargainTask(GSBargainBean aGSBargainBean,String aOldId)throws GSException {
         GSBargainDAO tGSBargainDAO = new GSBargainDAO();
         GSBargainBean tGSBargainBean=tGSBargainDAO.queryBargain(aGSBargainBean.getGs_bgn_id());
         String tType=tGSBargainBean.getGs_bgn_type();
         //判断是否是主合同
         if(tType.equals("1")){
             
             aGSBargainBean.setGs_bgn_mainserial(aGSBargainBean.getGs_bgn_serial());
             
           //判断是否修改合同编号
           if(!tGSBargainBean.getGs_bgn_serial().equals(aGSBargainBean.getGs_bgn_serial())){
              
             // 修改副合同编号
             if (tGSBargainDAO.modifyBargainId(aGSBargainBean.getGs_bgn_serial(),aOldId) == false) {
                 throw new GSException("修改副合同编号失败！");
               }
            }
         } 
        
             //修改合同信息
             if (tGSBargainDAO.modifyBargain(aGSBargainBean,aOldId) == false) {
                 throw new GSException("修改合同信息失败！");
               }
         }
     
     /**
      * 修改合同费用信息
      * @param aGSBargainBean
      * @throws GSException
      */
      public static void modifyBargainChargeTask(GSBargainChargeBean aGSBargainChargeBean)throws GSException {
          GSBargainDAO tGSBargainDAO = new GSBargainDAO();
              //修改合同信息
              if (tGSBargainDAO.modifyBargainCharge(aGSBargainChargeBean) == false) {
                  throw new GSException("修改合同费用信息失败！");
                }
     }
     /**
      * 链接读取上传文件（暂不调用）
      * @param aForm
      * @throws GSException
      */ 
     public void getBargainCont(GSBaseForm aForm) throws GSException{
    	 FileInputStream tFileInput = null;
    	 ServletOutputStream tOutputStream = null;
    	 try{
             String tBgnId = aForm.getRequest().getParameter("bgnId");
             GSBargainDAO tBargDAO = new GSBargainDAO();
//             GSBargainBean tBargBean = tBargDAO.queryBargain(tBgnId);
             GSBargainBean tBargBean = tBargDAO.queryBargainById(tBgnId);
             String tFileName = tBargBean.getGs_bgn_filename();
             
	    	 String tPath = GSSystemConfigurator.getParam("gs.upload.savepath");
	    	 String tPathFile = tPath + File.separator + tFileName;
	    	 File tFile = new File(tPathFile);
	    	 if(!tFile.exists()){
	    		 GSLogWriter.error(this,"文件不存在");
	    		 throw new GSException("文件不存在");
	    	 }else{
	    		 tFileInput = new FileInputStream(tFile);
                 long length = tFile.length();
	             aForm.getResponse().setContentType("application/x-msdownload");
                 aForm.getResponse().setContentLength((int)length);
	             aForm.getResponse().setHeader("Content-Disposition",
	                     "attachment;filename=" + GSBaseManager.toUtf8String(tFileName));
	    		 tOutputStream = aForm.getResponse().getOutputStream();
	    		 byte[] tBt = new byte[1024];
/*	    		 int tRs = tFileInput.read(tBt);
	    		 while(tRs != -1){
	    			 tOutputStream.write(tBt,0,tRs);
	    			 tRs = tFileInput.read(tBt);
	    		 }
*/
                 int k = 0;
                 while((long)k < length)
                 {
                     int j = tFileInput.read(tBt, 0, 1024);
                     k += j;
                     aForm.getResponse().getOutputStream().write(tBt, 0, j);
                 }

                 tFileInput.close();
	    	 }
    	 }catch(GSException ie){
    		 throw ie;
    	 }catch(Exception e){
    		 GSLogWriter.error(this,e.toString());
    		 throw new GSException(e.toString());
    	 }finally{
    		 try{
    			 if(tFileInput != null){
    				 tFileInput.close();
    			 }
    		 }catch(Exception e){
    			 e.printStackTrace();
    		 }
    	 }
    	 
    	 
     }
     
     /**
      * 添加合同修改信息
      * @param aGSBargainBean
      * @throws GSException
      */
     public static void addBargainModfiyTask(GSBargainModfiyBean aGSBargainModfiyBean)throws GSException {
         GSBargainDAO tGSBargainDAO = new GSBargainDAO();
            
             //添加合同修改信息
             if (tGSBargainDAO.addBargainModfiy(aGSBargainModfiyBean) == false) {
                 throw new GSException("添加合同修改信息失败！");
             }
         }
     
     /**
      * 查询合同修改信息
      * @param aBgnSerial
      * @return        
      * @throws GSException
      */
     public static ArrayList getBargainModfiy(String aBgmSerial) throws GSException{
         ArrayList tList=new ArrayList();
         try{
             GSBargainDAO tGSBargainDAO = new GSBargainDAO();
             tList = tGSBargainDAO.queryBargainModfiy(aBgmSerial);
             
         }catch(GSException e){
             throw e;
         }catch(Exception e){
             GSLogWriter.error(e.toString());
             throw new GSException(GSException.E10021,GSException.E10021_MSG);
         }
         return tList;
     }
     
     /**
      * 添加合同修改内容信息
      * @param aGSBargainBean
      * @throws GSException
      */
     public static String addBargainModfiyContent(GSBargainBean aGSBargainBean,String aDelfile,FormFile tNewFile)throws GSException {
         StringBuffer tContent = new StringBuffer();
         GSBargainDAO tGSBargainDAO = new GSBargainDAO(); 
         GSBargainBean tGSBargainBean=tGSBargainDAO.queryBargain(aGSBargainBean.getGs_bgn_id());
         if(!tGSBargainBean.getGs_bgn_usertype().equals(aGSBargainBean.getGs_bgn_usertype())){
             tContent.append("修改客户类型 ");
         }
         if(!tGSBargainBean.getGs_bgn_userid().equals(aGSBargainBean.getGs_bgn_userid())){
             tContent.append("修改客户名称 ");
         }
         if(!tGSBargainBean.getGs_bgn_content().equals(aGSBargainBean.getGs_bgn_content())){
             tContent.append("修改合同（协议）内容 ");
         }
         if(aDelfile.equals("2")){
             tContent.append("修改相关文件 ");
         }
         if(aDelfile.equals("new")){
             if(!(tNewFile.getFileSize()==0)){
             tContent.append("修改相关文件 ");
             }
         }
         if(!tGSBargainBean.getGs_bgn_serial().equals(aGSBargainBean.getGs_bgn_serial())){
             tContent.append("修改编号 ");
         }
         if(!tGSBargainBean.getGs_bgn_term().equals(aGSBargainBean.getGs_bgn_term())){
             tContent.append("修改期限 ");
         }
         
         
             
         return tContent.toString();
     }
}
